<?php
// $Id$

/**
 * @file
 * Implementation of drupal basic hooks
 */

/**
 * Implementation of hook_help().
 */
function archery_help($path, $arg) {
  switch ($path) {
    case 'admin/help#upload':
      $output = '<p>' . t('Module to manage archery scoring.') . '</p>';
      return $output;
  }
}

/**
 * Implementation of hook_perm().
 */
function archery_perm() {
  return array(
    'access archery' => array(
      'title' => t('Use the archery system'),
      'description' => t('Allows user to submit scores and view their history.'),
    ),
    'administer archery' => array(
      'title' => t('Manage the archery system'),
      'description' => t('Allows user to verify archers, scores and perform other administrative functions.'),
    ),
  );
}

/**
 * Implementation of hook_menu().
 */
function archery_menu() {
  $items['archery/history'] = array(
    'title' => 'Score History',
    'description' => 'View score history',
    'page callback' => 'archery_page_history',
    'access arguments' => array('access archery'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['archery/submit'] = array(
    'title' => 'Score Submission',
    'description' => 'Submit a score to the system.',
    'page callback' => 'archery_page_submit',
    'access arguments' => array('access archery'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Implementation of hook_user_login().
 * Setup our bow object
 */
function archery_user_login(&$edit, &$account, $category = NULL) {
  $bow = new archeryBow($account->uid);
  drupal_set_session('bow', $bow);
}

/**
 * Implementation of hook_user_logout().
 * Destroy our bow object
 */
function archery_user_logout(&$edit, &$account, $category = NULL) {
  unset($_SESSION['bow']);
}

function archery_user($op, &$edit, &$account, $category = NULL) {
  drupal_set_message("Op is: $op");
}

/**
 * Implementation of hook_user_form().
 * Display editable form fields to user on profile if needed
 */
function archery_user_form(&$edit, &$account, $category = NULL) {
  $form = _archery_user_details(&$account);
  if(!empty($form['archery'])) {
    return $form;
  }
}

/**
 * Implementation of hook_user_register().
 */
function archery_user_register(&$edit, &$account, $category = NULL) {
  return _archery_user_details(&$account);
}

/**
 * Generate form to gather archery specific user details.
 */
function _archery_user_details(&$account) {
  $form = array();
  $form['archery'] = array(
  '#type' => 'fieldset',
  '#title' => t('Archery settings'),
  '#weight' => 4);
  if(!isset($account->full_name)) {
    $form['archery']['archery_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Full Name'),
      '#size' => 64,
      '#maxlength' => 64,
      '#description' => t('Please enter your full name.'),
    );
  }
  if(!isset($account->dob)) {
    $form['archery']['archery_dob'] = array(
      '#type' => 'date',
      '#title' => t('Date of Birth'),
      '#description' => t('Please enter your date of birth.'),
    );
  }
  if(!isset($account->sex)) {
    $form['archery']['archery_sex'] = array(
      '#type' => 'radios',
      '#title' => t('Sex'),
      '#default_value' => 'M',
      '#options' => array('M' => t('Male'), 'F' => t('Female')),
      '#description' => t('Please indicate your sex.'),
    );
  }
  if(TRUE) { //@TODO check if recurve bow enabled
    $form['archery']['archery_recurve'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Recurve Bow'),
      '#default_value' => 0,
      '#description' => t('Enable recurve bow for the score system.'),
    );
  }
  if(TRUE) { //@TODO check if recurve bow enabled
    $form['archery']['archery_compound'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Compound Bow'),
      '#default_value' => 0,
      '#description' => t('Enable compound bow for the score system.'),
    );
  }
  return $form;
}

/**
 * Implementation of hook_user_insert().
 */
function archery_user_insert(&$edit, &$account, $category = NULL) {
  //Save extra user data to drupal user
  $dob = $edit['archery_dob']['day'].'-'.$edit['archery_dob']['month'].'-'.$edit['archery_dob']['year'];
  $extra_data = array(
    'full_name' => $edit['archery_name'],
    'sex' => $edit['archery_sex'],
    'dob' => $dob,
  );
  user_save($account, $extra_data);
  //Insert bow data
  if($edit['archery_recurve'] == 1) {
    $fields = array('uid' => $account->uid, 'type' => 'R');
    db_insert('bow')->fields($fields)->execute();
  }
  if($edit['archery_compound'] == 1) {
    $fields = array('uid' => $account->uid, 'type' => 'C');
    db_insert('bow')->fields($fields)->execute();
  }
  $edit = NULL;
}

/**
 * Implementation of hook_user_validate().
 */
function archery_user_validate(&$edit, &$account, $category = NULL) {
  if(!preg_match("/^([a-zA-Z'-]+\s*){2,5}$/",$edit['archery_name'])) { //Allow ' for things like O'mally, Drupal will escape it.
    form_set_error('archery_name', 'Name invalid, must consist of at least 2 parts  (first last).');
  }
  if($edit['archery_sex'] != 'M' && $edit['archery_sex'] != 'F') { //Sex invalid
    form_set_error('archery_sex', 'You must indicate your sex.');
  }
  if($edit['archery_recurve'] != 1 && $edit['archery_compound'] != 1) { //No bows selected
    form_set_error('archery_recurve', 'You must enable at least one bow.');
  }
  if($edit['archery_dob']['year'] > (date('Y')-1) && $edit['archery_dob']['year'] > (date('Y')-120)) { //Basic date of birth validation
    form_set_error('archery_dob', 'Please enter your date of birth correctly.');
  }
}

/**
 * Implementation of hook_user_delete().
 */
function archery_user_delete(&$edit, &$account, $category = NULL) {
  $result = db_query('SELECT bid FROM {bow} WHERE `uid` = :uid', array(':uid' => $account->uid);
  foreach($result as $result) {
    db_delete('score')->condition('bid', $result->bid)->execute();
  }
  db_delete('bow')->condition('uid', $account->uid)->execute();
}
